<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <span style="color: red;">说明：1.十三薪：上半年离职人员发放半年，下半年离职人员发放全年。
          2.2026年发放的十三薪、年度考核奖发放月份：2025年在职月份；发放标准：以2025年发放标准为基础。
          3.13%房补应与你单位07月工资表中房补一致（按照原人事处通知房补自2023年01月停止更新计算）。
          4.按照《关于调整垦区职工基本医疗保险单位缴费比例的通知》（北大荒集文【2025】16号）文件要求，职工医疗保险单位缴费比例调整至12%。
          单位：元
        </span>
        <a-row>
          <a-col :xs="12" :sm="12">
            <a-form-model-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <j-dict-select-tag type="list" v-model="model.year" dictCode="year" placeholder="请选择年度"
                                 @change="handleYearChange" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="派遣人员、退休返聘人员、借调人员费用明细表" :key="refKeys[0]" :forceRender="true">
        <j-editable-table :ref="refKeys[0]" :loading="cwPpryTable.loading" :columns="cwPpryTable.columns"
                          :dataSource="cwPpryTable.dataSource" :maxHeight="300" :disabled="formDisabled" :rowNumber="true"
                          :rowSelection="true" :actionButton="true" @valueChange="handleValueChange" />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { mapState } from 'vuex'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { getAction } from '@/api/manage'

export default {
  name: 'CwPpryTjForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: { year: "" },
      validatorRules: {
        unit: [
          { required: true, message: '请输入单位!' },
        ],
        year: [
          { required: true, message: '请输入年度!' },
        ],
      },
      addDefaultRowNum: 1,
      refKeys: ['cwPpry'],
      tableKeys: ['cwPpry'],
      activeKey: 'cwPpry',
      confirmLoading: false,
      // 新增：需要跳过计算的人员类型集合（统一管理，方便维护）
      noCalculateTypes: ['退休返聘', '所派遣无保险'], // 请根据实际字典值修改
      // 派遣人员、退休返聘人员、借调人员费用明细表
      cwPpryTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '姓名',
            key: 'name',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '院派遣/所派遣、退休返聘、借调',
            key: 'dispatchY',
            type: FormTypes.select,
            dictCode: "dispatch_y",
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '岗位工资',
            key: 'postWage',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '26年薪级工资',
            key: 'incrementalStep',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '生活性补贴',
            key: 'livingAllowance',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '工作性津贴',
            key: 'workAllowance',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '卫生费',
            key: 'sanitationFee',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '艰苦边远补贴',
            key: 'jkbybt',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '保健费（测试中心）',
            key: 'healthSubsidies',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '13%房补',
            key: 'housingSubsidy',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '基础绩效奖',
            key: 'jcjxj',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '25年薪级工资',
            key: 'xjgz',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '年度绩效奖',
            key: 'meritPay',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '安全奖/未休假补贴',
            key: 'safety',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '大额医保 (元/年/人)',
            key: 'deyb',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '取暖费',
            key: 'heatingFee',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '月应发合计',
            key: 'monthlyTotal',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '十三薪',
            key: 'thirteenSalary',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '社保缴费基数（年）',
            key: 'socialSecurityBase',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '医保缴费基数（年）',
            key: 'medicalInsuranceBase',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '公积金基数（年）',
            key: 'housingFundBase',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '养老保险（16%）',
            key: 'pensionInsurance',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '医疗保险（12%）',
            key: 'medicalInsurance',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '失业保险（0.5%）',
            key: 'unemploymentInsurance',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '工伤保险（0.35%）',
            key: 'employmentInjuryInsurance',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '公积金（12%）',
            key: 'housingFund',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '全年工资小计',
            key: 'annualSalary',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '全年社保及公积金共计',
            key: 'totalSocialSecurity',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '派遣服务费',
            key: 'dispatchServiceFee',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
          {
            title: '合计',
            key: 'total',
            type: FormTypes.input,
            width: "200px",
            placeholder: '自动计算',
            defaultValue: '0.0',
            disabled: true,
            validateRules: [{
              pattern: /^\d+(\.\d{1,2})?$/,
              message: "${title}格式不正确"
            }]
          },
        ]
      },
      url: {
        add: "/cw/cwPpryTj/add",
        edit: "/cw/cwPpryTj/edit",
        cwPpry: {
          list: '/cw/cwPpryTj/queryCwPpryByMainId'
        },
        getByYear: '/cw/cwPpryTj/list'
      },
      calcTimer: null,
      isManualChange: false
    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    scene: {
      type: String,
      default: '',
      required: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    ...mapState({ globalYear: state => state.app.globalYear })
  },
  watch: {
    globalYear(newVal) {
      if (!this.isManualChange) {
        this.model.year = newVal
      }
    },
    'model.year'(newVal, oldVal) {
      if (oldVal && newVal !== this.globalYear) {
        this.isManualChange = true
      }
    }
  },
  created() {
    this.model.year = this.globalYear
    const scene = this.scene
    this.currentScene = scene
    console.log('当前场景:', scene)
    if (scene === 'add') {
      this.handleYearChange(this.model.year)
    }
  },
  methods: {
    handleValueChange(event) {
      const { row, column, value, target } = event
      const rowId = row.rowId || row.id

      // 1. 处理人员类型（dispatchY）变化：实时重新计算
      if (column.key === 'dispatchY') {
        // 立即执行，无需防抖
        if (this.noCalculateTypes.includes(value)) {
          // 切换为跳过计算类型：清空所有计算字段
          const updateValues = {
            monthlyTotal: '0.00',
            thirteenSalary: '0.00',
            socialSecurityBase: '0.00',
            medicalInsuranceBase: '0.00',
            housingFundBase: '0.00',
            pensionInsurance: '0.00',
            medicalInsurance: '0.00',
            unemploymentInsurance: '0.00',
            employmentInjuryInsurance: '0.00',
            housingFund: '0.00',
            annualSalary: '0.00',
            totalSocialSecurity: '0.00',
            dispatchServiceFee: '0.00',
            total: '0.00'
          }
          target.setValues([{ rowKey: rowId, values: updateValues }])
        } else {
          // 切换为需要计算的类型：立即重新计算当前行
          this.calculateRowValues(target, rowId)
        }
        return // 处理完人员类型，直接返回
      }

      // 2. 处理数值字段变化（原有逻辑，保持防抖）
      const numericFields = [
        'postWage', 'incrementalStep', 'livingAllowance', 'workAllowance',
        'sanitationFee', 'jkbybt', 'healthSubsidies', 'housingSubsidy',
        'jcjxj', 'xjgz', 'meritPay', 'safety', 'deyb', 'heatingFee'
      ]

      // 只有非跳过类型的数值字段变化才计算
      if (numericFields.includes(column.key) && !this.noCalculateTypes.includes(row.dispatchY)) {
        clearTimeout(this.calcTimer)
        this.calcTimer = setTimeout(() => {
          this.calculateRowValues(target, rowId)
        }, 300)
      }
    },

    calculateRowValues(tableInstance, rowId) {
      // 同步最新的行数据（关键：避免使用旧的row数据）
      const allValues = tableInstance.getValuesSync({ validate: false }).values
      const currentRow = allValues.find(item => item.id === rowId || item.rowId === rowId)

      if (!currentRow) return

      // 再次校验：防止极端情况下的计算触发
      if (this.noCalculateTypes.includes(currentRow.dispatchY)) {
        return
      }

      const toNumber = (val) => {
        if (val === '' || val == null) return 0
        return parseFloat(val) || 0
      }

      const postWage = toNumber(currentRow.postWage)
      const incrementalStep = toNumber(currentRow.incrementalStep)
      const livingAllowance = toNumber(currentRow.livingAllowance)
      const workAllowance = toNumber(currentRow.workAllowance)
      const sanitationFee = toNumber(currentRow.sanitationFee)
      const jkbybt = toNumber(currentRow.jkbybt)
      const healthSubsidies = toNumber(currentRow.healthSubsidies)
      const housingSubsidy = toNumber(currentRow.housingSubsidy)
      const jcjxj = toNumber(currentRow.jcjxj)
      const xjgz = toNumber(currentRow.xjgz)
      const meritPay = toNumber(currentRow.meritPay)
      const safety = toNumber(currentRow.safety)
      const deyb = toNumber(currentRow.deyb)
      const heatingFee = toNumber(currentRow.heatingFee)

      // 月应发合计
      const monthlyTotal = postWage + incrementalStep + livingAllowance + workAllowance +
        sanitationFee + jkbybt + healthSubsidies + housingSubsidy + jcjxj

      // 十三薪
      const thirteenSalary = postWage + xjgz

      // 社保缴费基数（年）
      const socialSecurityBase = (postWage + xjgz + livingAllowance + workAllowance +
        jkbybt + jcjxj) * 12 + thirteenSalary

      // 医保缴费基数（年）
      const medicalInsuranceBase = (monthlyTotal - incrementalStep + xjgz) * 12

      // 公积金基数（年）
      const housingFundBase = (monthlyTotal - incrementalStep + xjgz) * 12 +
        thirteenSalary + meritPay + safety

      // 各项保险和公积金
      const pensionInsurance = socialSecurityBase * 0.16
      const medicalInsuranceCalc = medicalInsuranceBase * 0.12
      const unemploymentInsurance = socialSecurityBase * 0.005
      const employmentInjuryInsurance = socialSecurityBase * 0.0035
      const housingFund = housingFundBase * 0.12

      // 全年工资小计
      const annualSalary = monthlyTotal * 12 + thirteenSalary + meritPay + safety

      // 全年社保及公积金共计
      const totalSocialSecurity = pensionInsurance + medicalInsuranceCalc +
        unemploymentInsurance + employmentInjuryInsurance +
        housingFund + deyb

      // 派遣服务费（四舍五入取整）
      const dispatchServiceFee = Math.round((annualSalary + heatingFee + totalSocialSecurity) * 0.03)

      // 合计
      const total = annualSalary + heatingFee + totalSocialSecurity + dispatchServiceFee

      const updateValues = {
        monthlyTotal: this.formatNumber(monthlyTotal),
        thirteenSalary: this.formatNumber(thirteenSalary),
        socialSecurityBase: this.formatNumber(socialSecurityBase),
        medicalInsuranceBase: this.formatNumber(medicalInsuranceBase),
        housingFundBase: this.formatNumber(housingFundBase),
        pensionInsurance: this.formatNumber(pensionInsurance),
        medicalInsurance: this.formatNumber(medicalInsuranceCalc),
        unemploymentInsurance: this.formatNumber(unemploymentInsurance),
        employmentInjuryInsurance: this.formatNumber(employmentInjuryInsurance),
        housingFund: this.formatNumber(housingFund),
        annualSalary: this.formatNumber(annualSalary),
        totalSocialSecurity: this.formatNumber(totalSocialSecurity),
        dispatchServiceFee: this.formatNumber(dispatchServiceFee),
        total: this.formatNumber(total)
      }

      tableInstance.setValues([{
        rowKey: rowId,
        values: updateValues
      }])
    },

    formatNumber(value) {
      if (isNaN(value) || value == null) return '0.00'
      return parseFloat(value).toFixed(2)
    },

    addBefore() {
      this.cwPpryTable.dataSource = []
      this.$nextTick(() => {
        const tableInstance = this.$refs[this.refKeys[0]]
        if (tableInstance && tableInstance.getValuesSync) {
          const values = tableInstance.getValuesSync({ validate: false }).values
          if (values.length > 0) {
            const firstRow = values[0]
            // 非跳过类型才计算
            if (!this.noCalculateTypes.includes(firstRow.dispatchY)) {
              this.calculateRowValues(tableInstance, firstRow.id || firstRow.rowId)
            }
          }
        }
      })
    },

    editAfter() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.forceCalculateAllRows()
        }, 100)
      })

      if (this.model.id) {
        let params = { id: this.model.id }
        getAction(this.url.cwPpry.list, params).then(res => {
          if (res.success) {
            this.cwPpryTable.dataSource = res.result.records || []
            this.$nextTick(() => {
              setTimeout(() => {
                this.forceCalculateAllRows()
              }, 200)
            })
          }
        }).finally(() => {
          this.cwPpryTable.loading = false
        })
      }
    },

    checkTableReady() {
      return new Promise((resolve) => {
        const check = () => {
          const tableInstance = this.$refs[this.refKeys[0]]
          if (tableInstance && tableInstance.getValuesSync) {
            resolve(tableInstance)
          } else {
            setTimeout(check, 50)
          }
        }
        check()
      })
    },

    forceCalculateAllRows() {
      const tableInstance = this.$refs[this.refKeys[0]]
      if (!tableInstance || !tableInstance.getValuesSync) {
        console.warn('表格实例未就绪，重试中...')
        setTimeout(() => this.forceCalculateAllRows(), 100)
        return
      }

      try {
        const { values } = tableInstance.getValuesSync({ validate: false })
        if (values && values.length > 0) {
          values.forEach((row, index) => {
            const rowId = row.id || row.rowId
            if (rowId) {
              if (this.noCalculateTypes.includes(row.dispatchY)) {
                // 跳过类型：清空计算字段
                setTimeout(() => {
                  const updateValues = {
                    monthlyTotal: '0.00',
                    thirteenSalary: '0.00',
                    socialSecurityBase: '0.00',
                    medicalInsuranceBase: '0.00',
                    housingFundBase: '0.00',
                    pensionInsurance: '0.00',
                    medicalInsurance: '0.00',
                    unemploymentInsurance: '0.00',
                    employmentInjuryInsurance: '0.00',
                    housingFund: '0.00',
                    annualSalary: '0.00',
                    totalSocialSecurity: '0.00',
                    dispatchServiceFee: '0.00',
                    total: '0.00'
                  }
                  tableInstance.setValues([{ rowKey: rowId, values: updateValues }])
                }, index * 50)
              } else {
                // 普通类型：计算
                setTimeout(() => {
                  this.calculateRowValues(tableInstance, rowId)
                }, index * 50)
              }
            }
          })
        }
      } catch (error) {
        console.error('强制计算失败:', error)
      }
    },

    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },

    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main,
        cwPpryList: allValues.tablesValue[0].values,
      }
    },

    validateError(msg) {
      this.$message.error(msg)
    },

    close() {
      this.visible = false
      this.$emit('close')
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },

    async handleYearChange(year) {
      if (!year) {
        this.model = { unit: this.model.unit }
        this.cwPpryTable.dataSource = []
        return
      }

      this.confirmLoading = true
      this.cwPpryTable.loading = true

      try {
        const yearResponse = await getAction(this.url.getByYear, { year })

        if (yearResponse.success && yearResponse.result.records.length > 0) {
          const mainRecord = yearResponse.result.records[0]
          this.model = {
            ...this.model,
            ...mainRecord
          }

          if (mainRecord.id) {
            const ppryResponse = await getAction(this.url.cwPpry.list, { id: mainRecord.id })
            if (ppryResponse.success) {
              this.cwPpryTable.dataSource = ppryResponse.result.records || []
            } else {
              this.$message.warning('获取费用明细表数据失败：' + (ppryResponse.message || '未知错误'))
              this.cwPpryTable.dataSource = []
            }
          } else {
            this.$message.warning('未获取到费用明细表关联ID，无法加载数据')
            this.cwPpryTable.dataSource = []
          }
        } else {
          this.$message.warning(yearResponse.message || '该年度暂无数据')
          this.cwPpryTable.dataSource = []
          this.model.id = undefined
        }
      } catch (error) {
        console.error('查询接口异常：', error)
        this.$message.error('查询失败，请刷新页面重试或联系管理员')
        this.cwPpryTable.dataSource = []
      } finally {
        this.confirmLoading = false
        this.cwPpryTable.loading = false
      }
    }
  }
}
</script>

<style scoped></style>